package com.bc.bcapi.service;

import com.bc.bcapi.dao.T_User_seller_infoMapper;
import com.bc.bccore.redis.RedisService;
import com.bc.bccore.webconfig.WebConfig;
import com.bc.bcmodel.domain.T_User_buyer_infoModel;
import com.bc.bcmodel.domain.T_User_seller_infoModel;
import com.bc.bcmodel.enums.EmailTemplateEnum;
import com.bc.bcmodel.enums.IntegralRecordEnum;
import com.bc.bcmodel.req.UserActivateReq;
import com.bc.bcmodel.req.UserPasswordUpdateReq;
import com.bc.bcmodel.req.UserPasswordRegisterReq;
import com.bc.bcmodel.resp.MngSendEmailResp;
import com.bc.commoncore.security.AES;
import com.bc.commoncore.util.*;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Name UserPassportService
 * @Description TODO
 * @Author douhaichao
 * @Date 2018/9/27 10:59
 * @Version 1.0
 **/
@Service
public class UserSellerPassportService {

    @Resource
    T_User_seller_infoMapper t_user_seller_infoMapper;
    @Resource
    T_Integral_recordService t_integral_recordService;
    @Resource
    T_User_walletService t_user_walletService;
    @Resource
    T_Mng_email_sysService t_mng_email_sysService;
    @Resource
    RedisService redisService;

    /**
     * 注册激活
     *
     * @param req
     * @return
     */
    public JsonResult activate(UserActivateReq req) {
        //base params check
        HttpReturnRnums paramsCheckEnum = req.paramsCheck();
        if (paramsCheckEnum != HttpReturnRnums.Success) {
            return new JsonResult(paramsCheckEnum);
        }
        UserPasswordRegisterReq userPasswordRegisterReq = null;
        try {
            String code = AES.aesDecrypt(req.getCode());
            userPasswordRegisterReq = JsonUtil.str2obj(code, UserPasswordRegisterReq.class);
        } catch (Exception e) {
        }
        if (userPasswordRegisterReq == null) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        String key = "seller:activate:" + userPasswordRegisterReq.getUser_id();
        String value = redisService.get(key);
        if (!StringUtils.isEmpty(value)) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }

        String userId = userPasswordRegisterReq.getUser_id();
        String email = userPasswordRegisterReq.getEmail();
        T_User_seller_infoModel queryModel = new T_User_seller_infoModel();
        queryModel.setEmail(email);
        queryModel.setUser_id(userId);
        T_User_seller_infoModel queryResultModel = t_user_seller_infoMapper.findByNamedParam(queryModel);
        if (queryResultModel == null) {
            return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
        }
        if (StringUtils.equals("1", queryResultModel.getStatus())) {
            return new JsonResult(HttpReturnRnums.Success);
        }

        T_User_seller_infoModel updateModel = new T_User_seller_infoModel();
        updateModel.setUser_id(userId);
        updateModel.setStatus("1");
        t_user_seller_infoMapper.update(updateModel);

        //注册用户+积分
        t_integral_recordService.threadInsertIntegralRecord(IntegralRecordEnum.ZCYH, userId, userId);
        //邀请注册加积分
        addInviteIntegral(userId);
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * 邀请注册加积分
     */
    private void addInviteIntegral(String userId) {
        T_User_seller_infoModel t_user_seller_infoModel = new T_User_seller_infoModel();
        t_user_seller_infoModel.setUser_id(userId);
        T_User_seller_infoModel resultUserSeller =
                t_user_seller_infoMapper.findByNamedParam(t_user_seller_infoModel);
        //获取用户邀请码=邀请人的用户ID
        String invite_user_id = resultUserSeller.getInvite_code();
        t_integral_recordService.threadInsertIntegralRecord(IntegralRecordEnum.YQHYZC, userId, invite_user_id);
    }

    /**
     * 修改密码
     */
    public JsonResult updatePwd(UserPasswordUpdateReq req,
                                HttpServletRequest request) {
        if (!req.getNew_pwd().equals(req.getNew_pwd_confirm())) {
            return new JsonResult(HttpReturnRnums.PASSWD_NOT_EQUAL);
        }
        T_User_seller_infoModel t_user_seller_infoModel = new T_User_seller_infoModel();
        t_user_seller_infoModel.setUser_id(req.getUser_id());
        t_user_seller_infoModel.setPassword(Digest.signMD5(req.getOld_pwd(), Digest.ENCODE));
        T_User_seller_infoModel result = t_user_seller_infoMapper.findByNamedParam(t_user_seller_infoModel);
        if (result == null) {
            return new JsonResult(HttpReturnRnums.LOGON_NAME_PWD_NET_MATCH);
        }
        String email = result.getEmail();
        /**设置激活地址开始*/
        req.setEmail(email);
        req.setCreate_time(DateUtil.getToday());
        String code = JsonUtil.obj2string(req);
        code = AES.aesEncrypt(code);
        try {
            code = URLEncoder.encode(code, "utf-8");
        } catch (UnsupportedEncodingException e) {
        }
        String url = WebConfig.getSitePath() + "/userpassport/updatepwdactivate?code=" + code;
        /**设置激活地址结束*/
        //发送修改密码邮件
        List<MngSendEmailResp> list = new ArrayList<MngSendEmailResp>();
        MngSendEmailResp zhanghao = new MngSendEmailResp();
        zhanghao.setKey("email");
        zhanghao.setValue(email);
        list.add(zhanghao);
        MngSendEmailResp callbackUrl = new MngSendEmailResp();
        callbackUrl.setKey("callbackurl");
        callbackUrl.setValue(url);
        list.add(callbackUrl);
        t_mng_email_sysService.sendSystemEmailSync(
                EmailTemplateEnum.MODIFY_PWD, email, JsonUtil.obj2string(list), request);
        return new JsonResult();
    }

    /**
     * 忘记密码
     */
    public JsonResult forgotPwd(UserPasswordUpdateReq req,
                                HttpServletRequest request) {
        if (StringUtils.isEmpty(req.getEmail())) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        T_User_seller_infoModel t_user_seller_infoModel = new T_User_seller_infoModel();
        t_user_seller_infoModel.setEmail(req.getEmail());
        T_User_seller_infoModel result = t_user_seller_infoMapper.findByNamedParam(t_user_seller_infoModel);
        if (result == null) {
            return new JsonResult(HttpReturnRnums.USER_NOT_EXIST);
        }
        String newPwd = RandomCodeStrGenerator.generateCode(6);

        req.setNew_pwd(newPwd);
        String email = req.getEmail();
        req.setUser_id(result.getUser_id());
        req.setCreate_time(DateUtil.getToday());
        String code = JsonUtil.obj2string(req);
        code = AES.aesEncrypt(code);
        try {
            code = URLEncoder.encode(code, "utf-8");
        } catch (UnsupportedEncodingException e) {
        }
        //TODO 这里的地址应该是小达给的地址，
        String url = WebConfig.getSitePath() + "/userpassport/setforgotpwdactivate?code=" + code;

        List<MngSendEmailResp> list = new ArrayList<MngSendEmailResp>();
        MngSendEmailResp zhanghao = new MngSendEmailResp();
        zhanghao.setKey("email");
        zhanghao.setValue(email);
        list.add(zhanghao);
        MngSendEmailResp callbackUrl = new MngSendEmailResp();
        callbackUrl.setKey("callbackurl");
        callbackUrl.setValue(url);
        list.add(callbackUrl);
        MngSendEmailResp passwrd = new MngSendEmailResp();
        passwrd.setKey("password");
        passwrd.setValue(newPwd);
        list.add(passwrd);
        t_mng_email_sysService.sendSystemEmailSync(
                EmailTemplateEnum.Reset_PWD, email, JsonUtil.obj2string(list), request);
        return new JsonResult();
    }

    /**
     * 激活修改密码
     */
    public JsonResult updatePwdActivate(UserActivateReq req) {
        UserPasswordUpdateReq userPasswordUpdateReq = null;
        String code = req.getCode();
        /**
         * 验证当前链接是否使用过
         * */
        String checkCode = Digest.signMD5(code, Digest.ENCODE);
        String key = "seller:updatepwdactivate:" + checkCode;
        String value = redisService.get(key);
        if (!StringUtils.isEmpty(value)) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        try {

            code = URLDecoder.decode(code);
            code = AES.aesDecrypt(code);
            userPasswordUpdateReq = JsonUtil.str2obj(code, UserPasswordUpdateReq.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userPasswordUpdateReq == null) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }

        if (StringUtils.isEmpty(userPasswordUpdateReq.getUser_id()) ||
                StringUtils.isEmpty(userPasswordUpdateReq.getEmail())) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        userPasswordUpdateReq.setNew_pwd(
                Digest.signMD5(userPasswordUpdateReq.getNew_pwd(), Digest.ENCODE));

        int counter = t_user_seller_infoMapper.updatePwdActivate(userPasswordUpdateReq);
        redisService.set(key, "1");
        return new JsonResult();
    }

    /**
     * 激活忘记密码
     */
    public JsonResult getForgotPwdActivate(UserActivateReq req) {
        String code = AES.aesDecrypt(req.getCode());

        /**
         * 验证当前链接是否使用过
         * */
        String checkCode = Digest.signMD5(code, Digest.ENCODE);
        String key = "seller:getforgotpwdactivate:" + checkCode;
        String value = redisService.get(key);
        if (!StringUtils.isEmpty(value)) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        UserPasswordUpdateReq data = JsonUtil.str2obj(code, UserPasswordUpdateReq.class);
        data.setCode(code);
        return new JsonResult(data);
    }

    /**
     * 设置激活密码
     */
    public JsonResult setForgotPwdActivate(UserPasswordUpdateReq req) {
        if (StringUtils.isEmpty(req.getCode())){
//                || StringUtils.isEmpty(req.getNew_pwd())
//                || StringUtils.isEmpty(req.getNew_pwd_confirm()))
            return new JsonResult(HttpReturnRnums.ParaError);
        }
//        if (!req.getNew_pwd().equals(req.getNew_pwd_confirm())) {
//            return new JsonResult(HttpReturnRnums.PASSWD_NOT_EQUAL);
//        }
        UserPasswordUpdateReq data = null;
        try {
            String code = URLDecoder.decode(req.getCode());
            code = AES.aesDecrypt(code);
            data = JsonUtil.str2obj(code, UserPasswordUpdateReq.class);
            if (data == null) {
                return new JsonResult(HttpReturnRnums.ParaError);
            }

            /**
             * 验证当前链接是否使用过
             * */
//            String checkCode = Digest.signMD5(code, Digest.ENCODE);
//            String key = "seller:setforgotpwdactivate:" + checkCode;
//            String value = redisService.get(key);
//            if (!StringUtils.isEmpty(value)) {
//                return new JsonResult(HttpReturnRnums.ParaError);
//            }
//            redisService.set(key, "1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserPasswordUpdateReq userPasswordUpdateReq = new UserPasswordUpdateReq();
        userPasswordUpdateReq.setUser_id(data.getUser_id());
        userPasswordUpdateReq.setEmail(data.getEmail());
        userPasswordUpdateReq.setNew_pwd(Digest.signMD5(data.getNew_pwd(), Digest.ENCODE));
        int counter = t_user_seller_infoMapper.updatePwdActivate(userPasswordUpdateReq);

        return new JsonResult();
    }
}
